//
//  PPRegisterViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/21/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPRegisterViewController.h"
#import "PPAccomplishViewController.h"

#import "PPNetworkService.h"

#import "DGGlobalTimerTask.h"
#import "DGGlobalTimerManager.h"
#import "DGGlobalTimerObserver.h"
#import "DGGlobalTimerObserverManager.h"
#import "DGGlobalTimerTaskManager.h"
#import "PPUserAgreementViewController.h"

@interface PPRegisterViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phontField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UIButton *actionButton;
@property (readwrite, nonatomic, strong) UIButton *registerButton;
@property (readwrite, nonatomic, strong) UIView *bottomView;
@property (readwrite, nonatomic, assign) CGFloat keyboardTop;
@property (readwrite, nonatomic, strong) DGGlobalTimerObserver *timerObserver;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (readwrite, nonatomic, strong) UIButton *hiddenButton;
@end

@implementation PPRegisterViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [[DGGlobalTimerObserverManager sharedInstance] removeGlobalTimerObserver:_timerObserver];
}
- (void)setShowKeyBoard:(BOOL)showKeyBoard{
    
    if (showKeyBoard) {
        
        [_phontField becomeFirstResponder];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    _keyboardTop = self.view.height;

    self.title = @"注册";

    self.view.backgroundColor = [UIColor whiteColor];

    {
//        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        leftView.backgroundColor = [UIColor clearColor];
//        _phontField.leftView = leftView;
//        _phontField.leftViewMode = UITextFieldViewModeAlways;

//        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        rightView.backgroundColor = [UIColor clearColor];
//        _phontField.rightView = rightView;
//        _phontField.rightViewMode = UITextFieldViewModeAlways;
    }

//    {
//        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        leftView.backgroundColor = [UIColor clearColor];
//        _codeField.leftView = leftView;
//        _codeField.leftViewMode = UITextFieldViewModeAlways;
//
//        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        rightView.backgroundColor = [UIColor clearColor];
//        _codeField.rightView = rightView;
//        _codeField.rightViewMode = UITextFieldViewModeAlways;
//    }
//
//
//    _bottomView = [[UIView alloc] init];
//    _bottomView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:_bottomView];
//
//    _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    _registerButton.enabled = NO;
//    [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
//    [_registerButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xffdd17]] stretchableImageByCenter] forState:UIControlStateNormal];
//    [_registerButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf9d430]] stretchableImageByCenter] forState:UIControlStateHighlighted];
//    [_registerButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf2f2f2]] stretchableImageByCenter] forState:UIControlStateDisabled];
//    [_registerButton addTarget:self action:@selector(registerButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
//    [_bottomView addSubview:_registerButton];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];


    __weak typeof(self)weakSelf = self;
    _timerObserver = [[DGGlobalTimerObserver alloc] init];
    _timerObserver.key = @"register_verify_code_timer";
    _timerObserver.identifier = @"register_button";
    _timerObserver.initializedBlock = ^(NSTimeInterval remains){
        [weakSelf layoutActionButtonWithRemains:remains];
    };
    _timerObserver.triggeredBlock = ^(NSTimeInterval remains){
        [weakSelf layoutActionButtonWithRemains:remains];
    };
    _timerObserver.completedBlock = ^{
        [weakSelf layoutActionButtonWithRemains:0];
    };
    [[DGGlobalTimerObserverManager sharedInstance] addGlobalTimerObserver:_timerObserver];
    
    
    {
        //        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        //        leftView.backgroundColor = [UIColor clearColor];
        //        _passwordField.leftView = leftView;
        //        _passwordField.leftViewMode = UITextFieldViewModeAlways;
        
        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 48, 46)];
        rightView.backgroundColor = [UIColor clearColor];
        _passwordField.rightView = rightView;
        _passwordField.rightViewMode = UITextFieldViewModeAlways;
        
        _hiddenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _hiddenButton.adjustsImageWhenHighlighted = NO;
        [_hiddenButton setImage:[UIImage imageNamed:@"code-off"] forState:UIControlStateNormal];
        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateHighlighted|UIControlStateSelected];
        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateSelected];
        [_hiddenButton sizeToFit];
        _hiddenButton.center = CGPointMake(rightView.width/2, rightView.height/2);
        _hiddenButton.bounds = CGRectMake(0, 0, 50, 60);
        [_hiddenButton addTarget:self action:@selector(hiddenButtonDidPressed:) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:_hiddenButton];
    }
    

}
- (void)hiddenButtonDidPressed:(UIButton *)button {
    button.selected = !button.selected;
    
    _passwordField.secureTextEntry = !button.selected;
}
- (void)didReceiveKeyboardWillChangeFrameNotification:(NSNotification *)notification {
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];

    CGRect rect = [[[UIApplication sharedApplication] keyWindow] convertRect:endRect toView:self.view];

    _keyboardTop = CGRectGetMinY(rect);

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|(curve << 16) animations:^{
        _bottomView.bottom = _keyboardTop;
    } completion:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _bottomView.frame = CGRectMake(0, _keyboardTop - 45, self.view.width, 45);

    _registerButton.frame = _bottomView.bounds;
}

- (void)layoutActionButtonWithRemains:(NSTimeInterval)remains {
    if(remains <= 0) {
        [_actionButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _actionButton.enabled = YES;
    } else {
        [_actionButton setTitle:[NSString stringWithFormat:@"%li秒", (long)round(remains)] forState:UIControlStateNormal];
        _actionButton.enabled = NO;
    }
}
///MARK: 注册
- (void)registerButtonDidPressed {

    [MobClick event:@"7"];

//    if(!_registerButton.enabled) {
//        return;
//    }



    if (_phontField.text.length <= 0 || [_phontField.text isEqualToString:@""]) {
        [self.navigationController.view toastMessage:@"请输入手机号"];
        return;
    }
    
    if (![NSString isMobileNumber:_phontField.text ]) {
        [self.navigationController.view toastMessage:@"手机号错误"];
        return;
    }
    
    if (_codeField.text.length <= 0 || [_codeField.text isEqualToString:@""]) {
        [self.navigationController.view toastMessage:@"请输入验证码"];
        return;
    }
    
    if (_passwordField.text.length <= 0 || [_passwordField.text isEqualToString:@""]) {
        [self.navigationController.view toastMessage:@"请输入密码"];

        return;
    }
        [self.view endEditing:YES];
    
    NSString *phone = _phontField.text;
    NSString *code = _codeField.text;
    NSString *pwd = _passwordField.text;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService verfyPhoneCodeWithPhoneNumber:phone genToken:@(0) code:code callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [hud hide:YES];

        if(error == nil) {
//            PPAccomplishViewController *accomplishViewController = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateViewControllerWithIdentifier:@"PPAccomplishViewController"];
            
    PPAccomplishViewController *accomplishViewController = [[PPAccomplishViewController alloc] init];
            accomplishViewController.phone = phone;
            accomplishViewController.pwd = pwd;
            [self.navigationController pushViewController:accomplishViewController animated:YES];
        } else {
            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
        }
    }];

}
- (IBAction)userAgreementButtonDidPress:(id)sender {
    PPUserAgreementViewController *vc = [[PPUserAgreementViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)actionButtonDidPressed:(UIButton *)sender {
    NSString *phoneString = _phontField.text;

    if([phoneString isValidPhoneNumber]) {

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

        __weak typeof(self)weakSelf = self;

        [PPNetworkService checkPhoneNumberValidWithPhoneNumber:phoneString callback:^(id data, NSError *error) {
            __strong typeof(weakSelf)strongSelf = weakSelf;

            if(strongSelf == nil) {
                return;
            }

            if(error == nil) {

                [PPNetworkService sendVerfyCodeWithPhoneNumber:phoneString type:1 callback:^(id data, NSError *error) {
                    __strong typeof(weakSelf)strongSelf = weakSelf;

                    if(strongSelf == nil) {
                        return;
                    }

                    if(error == nil) {
                        [hud hide:YES];

                        [[DGGlobalTimerManager sharedInstance] rescheduleGlobalTimerForTaskKey:@"register_verify_code_timer" interval:1 duration:60];

                    } else {
                        [hud hide:YES];

                        [strongSelf.navigationController.view toastMessage:error.networkPrompt];
                    }
                }];

            } else {
                [hud hide:YES];

                [strongSelf.navigationController.view toastMessage:error.networkPrompt];
            }
        }];

    } else {
        [self.navigationController.view toastMessage:@"请输入正确的手机号"];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    if([string isEqualToString:@"\n"]) {
//        if(textField == _phontField) {
//            [_codeField becomeFirstResponder];
//        } else {
//            [_codeField resignFirstResponder];
//        }
//
//        return NO;
//    }

//    NSString *phone = _phontField.text;
//    NSString *code = _codeField.text;

//    if(textField == _phontField) {
//        phone = [phone stringByReplacingCharactersInRange:range withString:string];
//    } else {
//        code = [code stringByReplacingCharactersInRange:range withString:string];
//    }

//    if(phone.length > 11 || code.length > 8) {
//        return NO;
//    }

//    _registerButton.enabled = (phone.length > 0 && code.length > 0);

   
   

    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    if (textField == _passwordField) {

        [self registerButtonDidPressed];
        
    }
    
    return YES;
}
@end
